<script type='text/javascript'>
    draw{{chartId}}()
/*    setupChart = function(data, selector){
      d3.select(selector)
        .selectAll("div")
        .data(data).enter()
        .append('div').attr('class', 'preview')
        .append('svg');
    }
*/
    
    
    function draw{{chartId}}(){  
      var opts = {{{ opts }}},
        data = {{{ data }}}
        
  var subCharts = [];  
  

  //if facet not provided for x or y make Dummy variable
  opts.facet.x = opts.facet.x ? opts.facet.x : "Dummy"
  opts.facet.y = opts.facet.y ? opts.facet.y : "Dummy"    
  if(opts.facet.x === "Dummy" || opts.facet.y === "Dummy") {
    data.forEach(function(d){
      d.Dummy = 1;
    })
  }

  var rows = d3.set(data.map(function(d){return d[opts.facet.y]})).values();
  var nrow = rows.length;
  var cols = d3.set(data.map(function(d){return d[opts.facet.x]})).values()
  var ncol = cols.length;
  
  var tuples = d3.merge(rows.map(function(row,irow){return cols.map(function(col,icol){return {key:row + "~" + col, values: {"row":irow, "col":icol} }})}))
    
  var grid = d3.layout.grid()
    .rows( nrow )
    .cols( ncol )
    .size([ opts.width, opts.height-100])
    .bands();
  
  var svgGrid = d3.select("#" + opts.id).append("svg")
    .attr("width", opts.width)
    .attr("height", opts.height);
   // .attr("transform", "translate(50,0)");

  grid(tuples);        

  tuples.forEach(function(cell,cellnum) {
    // Filter the data set for the x and y facets
    var filteredData = data.filter(function(d){
      return d[opts.facet.x] == cell.key.split('~')[1]
    });
    //split for now but could easily do all in one filter
    filteredData = filteredData.filter(function(d){
      return d[opts.facet.y] == cell.key.split('~')[0]
    });
    
    filteredData = d3.nest()
      .key(function(d){ return d[opts.facet.x] + "~" + opts.facet.y} ).sortKeys(d3.ascending)
      .key(function(d){ return d[opts.group] } )
      .entries(filteredData);
      
         nv.addGraph(function() {
           var chart = nv.models[opts.type]()
            .x(function(d) {
             return d[opts.x] })
            .y(function(d) { return d[opts.y] })
            .width(grid.nodeSize()[0])
            .height(grid.nodeSize()[1])
       
        {{{ chart }}}
          
        {{{ xAxis }}}

        {{{ x2Axis }}}
        
        {{{ yAxis }}}           
          
        
         if(opts.type==="pieChart" || opts.type==="sparklinePlus") {
           facetdata = facetdata[0].values;
         };

       var thiscell = svgGrid.append("g")
          .attr("class", "cell")
          .attr("id", cell.key )
          .attr("transform", "translate(" + cell.x + "," + cell.y + ")" )
         // .attr("width", grid.nodeSize()[0])
        //.attr("height", grid.nodeSize()[1]);

        thiscell
          .datum(filteredData[0].values)
          .transition().duration(500)
          .call(chart);

          nv.utils.windowResize(chart.update);
        });
      });
    };
</script>